<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	private $_id;

	public function getId()
	{
		return $this->_id;
	}

	/**
	 * @param string $cookieSalt
	 * @return boolean
	 */
	public function authenticate($cookieSalt = null)
	{
		$valid = false;
		if ($cookieSalt !== null) {
			$model = User::model()->findByPk($this->username);/* @var $model User */
			$valid = $model !== null && $model->encodePassword($model->password, $cookieSalt) === $this->password;
		} else {
			$model = User::model()->findByAttributes(array('username' => $this->username));
			if ($model !== null && $this->password === $model->password) {
				$valid = true;
				$salt = substr(uniqid(null, true), -6);
				$this->setState('salt', $salt);
				$this->setState('password', $model->encodePassword($model->password, $salt));
			}
		}
		if ($model === null) {
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		} elseif (!$valid) {
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		} else {
			$this->_id = $model->id;
			$this->username = $model->username;
			$this->errorCode = self::ERROR_NONE;
		}
		return $this->errorCode === self::ERROR_NONE;
	}
}
